package com.wgchao.authmanager.infrastructure.repository;

import com.wgchao.authmanager.domain.model.Agency;
import com.wgchao.authmanager.domain.repository.AgencyRepository;
import com.wgchao.authmanager.infrastructure.convert.em.AgencyInfoConvert;
import com.wgchao.authmanager.infrastructure.exception.IdNotExistException;
import com.wgchao.authmanager.infrastructure.exception.IdentifyUsedException;
import com.wgchao.authmanager.infrastructure.jpa.entity.AgencyInfo;
import com.wgchao.authmanager.infrastructure.jpa.repository.AgencyInfoJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @作者：wgchao
 * @时间：21:27 2020/4/25 0025
 * @用途：
 **/
@Component
public class AgencyRepsoitoryImpl implements AgencyRepository {
    @Autowired
    private AgencyInfoConvert agencyInfoConvert;
    @Autowired
    private AgencyInfoJpaRepository agencyInfoJpaRepository;

    @Override
    public String geneteAgencyCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String uStr = UUID.randomUUID().toString().toUpperCase();
        return "3702"+sdf.format(new Date())+uStr.split("-")[2];
    }

    @Override
    public void add(Agency agency) {
        if(agency.findId() == null || agency.findId().compareTo(0L) <= 0){
            //检查机构编号是否已存在
            AgencyInfo agencyInfo = agencyInfoJpaRepository.findFirstByAgencyCode(agency.getAgencyCode());
            if(agencyInfo != null){
                throw new IdentifyUsedException("机构编号已被占用");
            }
        }
        AgencyInfo agencyInfo = agencyInfoConvert.toEntity(agency);
        agencyInfo.setDel(false);
        agencyInfo = agencyInfoJpaRepository.save(agencyInfo);
    }

    @Override
    public void remove(Agency agency, String operator) {
        AgencyInfo agencyInfo = agencyInfoConvert.toEntity(agency);
        if(agencyInfo.getId() == null){
            throw new IdNotExistException("主键缺失");
        }
        agencyInfo.setDel(true);
        agencyInfo.setLastUpdateUser(operator);
        agencyInfo.setLastUpdateTime(new Date());
        agencyInfo = agencyInfoJpaRepository.save(agencyInfo);
    }

    @Override
    public Agency get(String id) {
        AgencyInfo agencyInfo = agencyInfoJpaRepository.findFirstByAgencyCodeAndDelFalse(id);
        if(agencyInfo == null){
            return null;
        }
        return agencyInfoConvert.toModel(agencyInfo);
    }
}
